package com.ssc.manager.admin.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ssc.manager.admin.dao.IPlayDao;
import com.ssc.manager.admin.entity.db.Play;
import com.ssc.manager.admin.service.IPlayDataService;
import com.ssc.manager.common.cache.Cache;
import com.ssc.manager.common.constant.SystemConstant;
import com.ssc.manager.common.system.SystemData;
import com.ssc.manager.common.utils.BetiingUtils;
import com.ssc.manager.common.utils.PlayUtils;

@Service
public class PlayDataService implements IPlayDataService {

	@Autowired
	private IPlayDao playDao;
	
	@Autowired
	private Cache cache;

	@Override
	public void initPlayData() {
		List<Play> list = playDao.selectList(new Play());
		for (Play play : list) {
			SystemData.addPlay(play);
		}
		cache.set(PlayUtils.findPlayDataKey(), list);
		List<String> codes = findGameCodes(list);
		for (String code : codes) {
			List<Play> sortPlays = findSortPlay(list,code);
			List<String> itemCodes =  findSortItems(sortPlays);
			SystemData.addItem(code, itemCodes);
			cache.set(PlayUtils.findItemDataKey(code), itemCodes);
			for(String item : itemCodes){
				cache.rightPush(PlayUtils.findPlayOddsKey(code), item);
			}
		}
	}

	/**
	 * 查询所有玩法名称
	 * 
	 * @param list
	 * @return
	 */
	private List<String> findGameCodes(final List<Play> list) {
		List<String> codes = new ArrayList<String>();
		for (Play play : list) {
			if (!codes.contains(play.getGameCode())) {
				codes.add(play.getGameCode());
			}
		}
		return codes;
	}

	private List<Play> findSortPlay(final List<Play> list, String gameCode) {
		List<Play> sortPlays = new ArrayList<Play>();
		for (Play play : list) {
			if (gameCode.equals(play.getGameCode())) {
				sortPlays.add(play);
			}
		}
		ComparatorUser comparator=new ComparatorUser();
		Collections.sort(sortPlays, comparator);
		return sortPlays;
	}

	class ComparatorUser implements Comparator {
		public int compare(Object arg0, Object arg1) {
			Play play0 = (Play) arg0;
			Play play1 = (Play) arg1;
			return play0.getGameIndex().compareTo(play1.getGameIndex());

		}
	}

	
	private List<String> findSortItems(List<Play> list){
		List<String> codes = new ArrayList<String>();
		for (Play play : list) {
			codes.add(BetiingUtils.findSumItemKey(play.getItemCode(),SystemConstant.TRADESELL));
			codes.add(BetiingUtils.findSumItemKey(play.getItemCode(),SystemConstant.TRADEBUY));
		}
		return codes;
	}
}
